package com.example.ecommercecommon.util;


import com.alibaba.fastjson.JSON;
import com.example.ecommercecommon.constant.CommonConstant;
import com.example.ecommercecommon.vo.LoginUserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Calendar;

@Slf4j
public class TokenParseUtil {


    /**
     * 根据本地存储的公钥获取到public key对象
     */
    private static PublicKey getPublicKey() throws Exception {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(
                new BASE64Decoder().decodeBuffer(CommonConstant.PUBLIC_KEY)
        );
        return KeyFactory.getInstance("RSA").generatePublic(keySpec);
    }


    /**
     * 通过公钥去解析JWT Token
     */
    private static Jws<Claims> parseToken(String token, PublicKey publicKey) throws Exception {
        return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
    }

    public static String convertToValidJson(String input) {
        // 去掉首尾的花括号
        String trimmedInput = input.substring(1, input.length() - 1);

        // 替换等号为冒号，并添加双引号
        String jsonStr = trimmedInput.replaceAll("(\\w+)=([^,}]+)", "\"$1\":\"$2\"");

        // 添加外层的花括号
        jsonStr = "{" + jsonStr + "}";
        return jsonStr;
    }

    /**
     * <h2>从 JWT Token 中解析 LoginUserInfo 对象</h2>
     */
    public static LoginUserInfo parseUserInfoFromToken(String token) throws Exception {
        if (null == token) {
            return null;
        }
        try {
            Jws<Claims> claimsJws = parseToken(token, getPublicKey());
            Claims body = claimsJws.getBody();

            // 检查Token是否过期
            if (body.getExpiration().before(Calendar.getInstance().getTime())) {
                return null;
            }

            log.info(body.get(CommonConstant.JWT_USER_INFO_KEY).toString());
            // 尝试解析Token中保存的用户信息
            LoginUserInfo loginUserInfo = JSON.parseObject(
                    (convertToValidJson(body.get(CommonConstant.JWT_USER_INFO_KEY).toString())),
                    LoginUserInfo.class
            );
            return loginUserInfo;
        } catch (Exception e) {
            // 打印出具体的错误位置和消息
            e.printStackTrace();
            // 可以选择抛出更具体的异常或进行其他处理
            throw e; // 或者根据需要重新抛出或处理这个异常
        }
    }

}